package com.leyou.role.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.role.mapper.RoleMapper;
import com.leyou.role.pojo.Role;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public PageResult<Role> rolePageQuery(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //添加分页条件
        PageHelper.startPage(page, rows);
        //封装查询条件，包括排序
        Example example = new Example(Role.class);
        //判断查询条件是否有值，有就封装条件
        if(!StringUtils.isBlank(key)){
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("role_name", "%"+key.toUpperCase()+"%");

        }
        //判断是否有排序字段   select * from tb_brand where name=xx order by name desc
        if(!StringUtils.isBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }
        //mybatis查询操作
        List<Role> roles = roleMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(roles)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //得到PageHelper的分页对象
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        //封装自定义的分页对象
        List<Role> list = pageInfo.getList();
        PageResult<Role> pageResult = new PageResult<>(pageInfo.getTotal(),
                list);

        return pageResult;
    }

    public List<Role> queryByPermission() {
        return roleMapper.selectAll();
    }

    public Role queryById(Long id) {
      return   roleMapper.selectByPrimaryKey(id);
    }
}
